import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import MusicAPI from '@/services/ant-design-pro/music';
import ProTable from '@ant-design/pro-table';
import { connect } from 'dva'

import CreateOrEdit from './components/CreateOrEdit'

const { deleteClassify } = MusicAPI;
const categories = {
    0: {
        text: "语种",
        label: "语种",
        value: 0,
        defaultValue: 0,
    },
    1: {
        text: "风格",
        label: "风格",
        value: 1,
        defaultValue: 1,
    },
    2: {
        text: "场景",
        label: "场景",
        value: 2,
        defaultValue: 2,
    },
    3: {
        text: "情感",
        label: "情感",
        value: 3,
        defaultValue: 3,
    },
    4: {
        text: "主题",
        label: "主题",
        value: 4,
        defaultValue: 4,
    }
};
const ClassifyTag = (props) => {
    const actionRef = useRef(); // 表格ref，便于自定义操作表格
    const { dispatch, classifyTags } = props;
    const [isModalVisible, setIsModalVisible] = useState(false),
        [editData, setEditData] = useState(undefined),
        [data, setData] = useState(classifyTags.sub || []);


    /**
     * 设置音乐数据到state
     * @returns obj(音乐列表)
     */
    const setClassify = async (isRefresh = false) => {
        let res;
        await dispatch({
            type: 'music/getClassifyTags',
            payload: {
                refresh: isRefresh
            },
            callback: async (result) => {
                res = await result.sub;
                setData(result.sub);
            }
        })

        return {
            data: res,
            success: true
        }
    }

    /**
     * 控制模态框显示与隐藏
     */
    const isShowModal = (show, record = undefined) => {
        setIsModalVisible(show);
        setEditData(record);
    };

    const delClassify = async (record) => {
        const result = await deleteClassify({
            id: record.id
        })
        if (result.status == 'ok') {
            await setClassify(true);
            actionRef.current.reload();
            message.success("删除成功");
        } else {
            message.error('删除失败：' + result.data.message);
            console.log(result.data.error);
        }
    }

    /**
     * 获取音乐列表
     * @param {obj} params 搜索参数
     * @returns obj(音乐列表)
     */
    const getData = (params) => {
        if (JSON.stringify(data) != "[]") {
            let name = params.name || "",
                category = params.category || "",
                result = data;
            if (name.trim().length > 0 || category) {
                result = data.filter((item, index) => {
                    if (name && category) {
                        return item.name.toLowerCase().indexOf(name.toLowerCase()) >= 0
                            && item.category == category
                    } else if (name) {
                        return item.name.toLowerCase().indexOf(name.toLowerCase()) >= 0
                    } else if (category) {
                        return item.category == category;
                    }
                })
            }
            return {
                data: result,
                success: true
            }
        }
        return setClassify();
    }

    const columns = [
        {
            title: '标题',
            dataIndex: 'name',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '类别',
            dataIndex: 'category',
            filters: true,
            onFilter: true,
            valueType: 'select',
            valueEnum: categories,
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a key="editable" onClick={() => isShowModal(true, record)}>
                    编辑
                </a>,
                <a rel="noopener noreferrer" key="del" onClick={() => delClassify(record)}>
                    删除
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable columns={columns} actionRef={actionRef} request={(params = {}, sort, filter) => {
                return getData(params);
            }}
                rowKey="id"
                search={{
                    labelWidth: 'auto'
                }} pagination={{
                    pageSize: 5,
                }} dateFormatter="string" headerTitle="高级表格" toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModal(true)}>
                        新建
                    </Button>,
                ]} />
            {
                isModalVisible ?
                    <CreateOrEdit
                        isModalVisible={isModalVisible}
                        isShowModal={isShowModal}
                        actionRef={actionRef}
                        initData={editData}
                        setData={setClassify}
                    /> : ""
            }
        </PageContainer>
    )
}

export default connect(({ music }) => ({ classifyTags: music.classifyTags }))(ClassifyTag);


